/*
 * Copyright 2013-2019 Xia Jun(3979434@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************************************
 *                                                                                     *
 *                        Website : http://www.farsunset.com                           *
 *                                                                                     *
 ***************************************************************************************
 */
package com.farsunset.cim.sdk.server.slc.handler;

import com.farsunset.cim.sdk.server.coder.AppMessageDecoder;
import com.farsunset.cim.sdk.server.coder.AppMessageEncoder;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.timeout.IdleStateHandler;

@Sharable
public class SlcUdpCIMNioSocketAcceptor extends UdpCIMNioSocketAcceptor {

    protected final boolean loadDeApp;
    protected final boolean loadIdle;
    protected final boolean usePlatformOptimization;
    protected final Map<String, ChannelHandler> appChannelHandlerMapByDeBefore;
    protected final Map<String, ChannelHandler> appChannelHandlerMapByDeAfter;


    public SlcUdpCIMNioSocketAcceptor(SlcBuilder builder) {
        super(builder);
        this.loadDeApp = builder.loadDeApp;
        this.loadIdle = builder.loadIdle;
        this.usePlatformOptimization = builder.usePlatformOptimization;
        this.appChannelHandlerMapByDeBefore = builder.appChannelHandlerMapByDeBefore;
        this.appChannelHandlerMapByDeAfter = builder.appChannelHandlerMapByDeAfter;
    }

    @Override
    protected void bindAppPort() {
        createAppEventGroup();
        Bootstrap bootstrap = createServerBootstrap(getAppBossGroup());
        bootstrap.handler(new ChannelInitializer<Channel>() {
            @Override
            public void initChannel(Channel ch) {
                for (Map.Entry<String, ChannelHandler> entry : appChannelHandlerMapByDeBefore.entrySet()) {
                    ch.pipeline().addLast(entry.getKey(), entry.getValue());
                }
                if (loadDeApp) {
                    ch.pipeline().addLast(new AppMessageDecoder());
                    ch.pipeline().addLast(new AppMessageEncoder());
                }
                for (Map.Entry<String, ChannelHandler> entry : appChannelHandlerMapByDeAfter.entrySet()) {
                    ch.pipeline().addLast(entry.getKey(), entry.getValue());
                }
                ch.pipeline().addLast(loggingHandler);
                if (loadIdle) {
                    ch.pipeline().addLast(new IdleStateHandler(readIdle, writeIdle, 0, TimeUnit.SECONDS));
                }
                ch.pipeline().addLast(SlcUdpCIMNioSocketAcceptor.this);
            }
        });

        ChannelFuture channelFuture = bootstrap.bind(appPort).syncUninterruptibly();
        channelFuture.channel().newSucceededFuture().addListener(future -> {
            String logBanner = "\n\n" +
                    "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" +
                    "*                                                                                   *\n" +
                    "*                                                                                   *\n" +
                    "*                   App Udp Server started on port {}.                           *\n" +
                    "*                                                                                   *\n" +
                    "*                                                                                   *\n" +
                    "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n";
            LOGGER.info(logBanner, appPort);
        });
        channelFuture.channel().closeFuture().addListener(future -> this.destroy(getAppBossGroup()));
    }

    public static class SlcBuilder extends Builder {
        private boolean loadDeApp = true;
        private boolean loadIdle = true;
        private boolean usePlatformOptimization;
        private final LinkedHashMap<String, ChannelHandler> appChannelHandlerMapByDeBefore = new LinkedHashMap<>();
        private final LinkedHashMap<String, ChannelHandler> appChannelHandlerMapByDeAfter = new LinkedHashMap<>();

        public SlcBuilder setLoadDeApp(boolean loadDeApp) {
            this.loadDeApp = loadDeApp;
            return this;
        }

        public SlcBuilder setLoadIdle(boolean loadIdle) {
            this.loadIdle = loadIdle;
            return this;
        }

        public SlcBuilder setUsePlatformOptimization(boolean usePlatformOptimization) {
            this.usePlatformOptimization = usePlatformOptimization;
            return this;
        }

        public SlcBuilder setAppChannelHandlerMapByDeBefore(LinkedHashMap<String, ChannelHandler> appChannelHandlerMapByDeBefore) {
            this.appChannelHandlerMapByDeBefore.clear();
            this.appChannelHandlerMapByDeBefore.putAll(appChannelHandlerMapByDeBefore);
            return this;
        }

        public SlcBuilder addAppChannelHandlerByDeBefore(String key, ChannelHandler channelHandler) {
            this.appChannelHandlerMapByDeBefore.put(key, channelHandler);
            return this;
        }

        public SlcBuilder setAppChannelHandlerMapByDeAfter(LinkedHashMap<String, ChannelHandler> appChannelHandlerMapByDeAfter) {
            this.appChannelHandlerMapByDeAfter.clear();
            this.appChannelHandlerMapByDeAfter.putAll(appChannelHandlerMapByDeAfter);
            return this;
        }

        public SlcBuilder addAppChannelHandlerByDeAfter(String key, ChannelHandler channelHandler) {
            this.appChannelHandlerMapByDeAfter.put(key, channelHandler);
            return this;
        }

        @Override
        public SlcUdpCIMNioSocketAcceptor build() {
            return new SlcUdpCIMNioSocketAcceptor(this);
        }

    }
}